using System;
using System.IO;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using RFS.Domain.Sys;

namespace RFS.BizLogic.Ports.Adapters
{

    
        public class BlobAliOssRepo : IBlobRepo
    {
        private IConfigT _config;

        private string AccessKeyId = "LTAI5tG3My56cvgqfJ41WaK3";

        private string AccessKeySecret = "6LJK7a3HC6xa9VPySrEONYf9aUICxJ";

        // private const string Endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // Replace with your region endpoint
        private const string Endpoint = "http://oss-cn-shenzhen.aliyuncs.com"; // Replace with your region endpoint
        private const string BucketName = "pingyuan-files";


        public BlobAliOssRepo(IConfigT config)
        {
            _config = config;

            AccessKeyId = _config.ConfigSys.AliYxAccessKey_ID;
            AccessKeySecret = _config.ConfigSys.AliYxAccessKey_secret;

            ossClient = new OssClient(Endpoint, AccessKeyId, AccessKeySecret);
            
            MakesurebucketIsGodd(BucketName);
        }

        void MakesurebucketIsGodd(string bn)
        {
            if (!  ossClient.DoesBucketExist(bn))
                ossClient.CreateBucket(new CreateBucketRequest(bn));
            
        }

        OssClient ossClient;

        public void PushData(string key, Stream stream)
        {
            
            
            // Initialize the OSS client
            var fn = GetRemotePath(key);
            ossClient.PutObject(BucketName, fn, stream);
        }

        private string _localTempFolder = "temp";

        string GetLocalFileName(string key)
        {
            return Path.Combine(_localTempFolder, key);
        }

        public Stream GetData(string key)
        {
            try
            {
                var remoteFileName = GetRemotePath(key);
                    var obj = ossClient.GetObject(BucketName, remoteFileName);
                    return obj.Content;
            }
            catch (OssException ex)
            {
                throw new Exception($"Ali Oss 出错: {ex.Message}", ex);
            }
        }

        public void Delete(string cId)
        {

            var fn = GetRemotePath(cId);
            ossClient.DeleteObject(BucketName, fn);
            
        }

        public bool Existed(string key)
        {
            var fn = GetRemotePath(key );

            return ossClient.DoesObjectExist(BucketName,fn);
        }


        string GetRemotePath(string key)
        {
            return $"contractsBlobData/{key}";
        }


        // public void T_Ossf()
        // {
        //     var an = Starter.StartApp(true);
        //     
        //  
        //
        //     var fn = "res/contract1.png";
        //     var rfn = "t1/rcontract1.png";
        //
        //
        //     // Initialize the OSS client
        //     var ossClient = new OssClient(Endpoint, AccessKeyId, AccessKeySecret);
        //
        //     // Upload a file
        //     UploadFile(ossClient, fn, rfn);
        //
        //     // List files in the bucket
        //     ListFiles(ossClient);
        //
        //     // Download a file
        //     DownloadFile(ossClient, rfn, "res/ded.png");
        //
        //    
        // }

        void UploadFile(OssClient ossClient, string localFilePath, string objectName)
        {
            try
            {
                // Upload the file
                using (var fileStream = File.OpenRead(localFilePath))
                {
                    ossClient.PutObject(BucketName, objectName, fileStream);
                }

                // Console.WriteLine($"File uploaded: {objectName}");
            }
            catch (OssException ex)
            {
                // Console.WriteLine($"Error uploading file: {ex.Message}");
            }
        }

        void ListFiles(OssClient ossClient)
        {
            try
            {
                // List objects in the bucket
                var listObjectsRequest = new ListObjectsRequest(BucketName);
                var listObjectsResult = ossClient.ListObjects(listObjectsRequest);

                Console.WriteLine("Files in the bucket:");
                foreach (var obj in listObjectsResult.ObjectSummaries)
                {
                    Console.WriteLine($"- {obj.Key}");
                }
            }
            catch (OssException ex)
            {
                Console.WriteLine($"Error listing files: {ex.Message}");
            }
        }

        void DownloadFile(OssClient ossClient, string objectName, string localFilePath)
        {
            try
            {
                // Download the file
                using (var fs = File.Create(localFilePath))
                {
                    var obj = ossClient.GetObject(BucketName, objectName);
                    // var obj = client.GetObject(bucketName, objectName);
                    using (var requestStream = obj.Content)
                    {
                        byte[] buf = new byte[1024];
                        // var fs = File.Open(downloadFilename, FileMode.OpenOrCreate);

                        var len = 0;
                        // 通过输入流将文件的内容读取到文件或者内存中。
                        while ((len = requestStream.Read(buf, 0, 1024)) != 0)
                        {
                            fs.Write(buf, 0, len);
                        }

                        fs.Close();
                    }

                    // Console.WriteLine("Get object succeeded");
                }

                // Console.WriteLine($"File downloaded: {localFilePath}");
            }
            catch (OssException ex)
            {
                // Console.WriteLine($"Error downloading file: {ex.Message}");
            }
        }
    }
    
    
        
}